package com.etone.smartAudit.apiIntercept;

import com.alibaba.fastjson.JSON;
import com.etone.daemon.util.JsonUtils;
import com.etone.smartFlow.common.StringUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ApiIntercept implements HandlerInterceptor {

    @Autowired
    private ApiConfig apiConfig;

    @Value("${api.intercept.path}")
    public String apiInterceptPaths;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Result result = apiConfig.checkParam(request);
        if (Result.SUCCESSFUL_CODE.equals(result.getCode())) {
            return true;
        } else {
            errorTokenMsg(response, result);
            return false;
        }
    }

    private void errorTokenMsg(HttpServletResponse response, Result result) {
        OutputStream os = null;
        try {
            //1.1 (设置输出的编码格式)指定输出到客户端的时候，这些文字使用UTF-8编码
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    public List<String> interceptPaths() {
        List<String> paths = new ArrayList<>();
        if (StringUtils.isNotEmpty(apiInterceptPaths)) {
            String[] split = apiInterceptPaths.split(",");
            if (split.length > 0) {
                paths.addAll(Arrays.asList(split));
            }
        }
        return paths;
    }

}
